<?php if (!defined("_ECRIRE_INC_VERSION")) return; if (class_exists('ProductModel')) return;
/**
 * EcataloguE
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage ecatalogue
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/EcataloguE
 */

/**
 *  ProductModel class 
 *
 *  @author Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com) 
 */
include_spip('classes/pdk_model'); 
include_spip('functions/pdk_common');
class ProductModel extends pdk_Model {   
    /**
     *  CurrencyModel
     */
    protected $currency_mdl;
    
    /**
     *  CompositeArticleModel
     */
    private $composite_art_mdl;
    
    public function __construct() {
        parent::__construct();
        $this->config_model();
        
        $this->currency_mdl = pdk_load_class('CurrencyModel','classes');
        $this->composite_art_mdl = pdk_load_class('CompositeArticleModel','classes');
        
        //$price_precision = lire_config('ecatalogue/price_pricision'); if (!$price_precision) $price_precision = 2;
    }
    
    function config_model() {
        // Define main table:
        $this->main_table = 'spip_ecatalogue_products';
        
        // Define primary key:
        $this->primary_key = 'id_article';
        
        // Define main table fields:
        $this->main_fields['id_article'] = 'id_article'; 
        $this->main_fields['price'] = 'price';
        $this->main_fields['priceold'] = 'priceold';
        $this->main_fields['sku'] = 'sku';
        $this->main_fields['quantity'] = 'quantity';    
        $this->main_fields['weight'] = 'weight';
        $this->main_fields['width'] = 'width';
        $this->main_fields['height'] = 'height';
        $this->main_fields['length'] = 'length';
        $this->main_fields['id_equipment'] = 'id_equipment';
        $this->main_fields['extra1'] = 'extra1';
        $this->main_fields['extra2'] = 'extra2';
        $this->main_fields['extra3'] = 'extra3';
        $this->main_fields['extra4'] = 'extra4';
        $this->main_fields['is_composite'] = 'is_composite';
        $this->main_fields['is_separate'] = 'is_separate';
        $this->main_fields['num_in_package'] = 'num_in_package';
        $this->main_fields['sold_in_packages'] = 'sold_in_packages';
        
        // Join spip_articles just for select queries
        $this->joins['spip_articles'] = 
            array('main_id'=>'id_article',
                  'join_id'=>'id_article',
                  'hard_join'=>false,
                  'join_type'=>'LEFT',
                  'fields'=>array('titre'=>'titre','id_rubrique'=>'id_rubrique','id_secteur'=>'id_secteur')
                  );
                                                                                 
         // Define validation rules:
         $this->validation->set_rules( 
            array(
                array(
                     'field'   => 'id_article',
                     'label'   => _T('ecatalogue:id_article'),
                     'rules'   => ''
                  ),
               array(
                     'field'   => 'price',
                     'label'   => _T('ecatalogue:price'),
                     'rules'   => ''
                  ),
               array(
                     'field'   => 'sku',
                     'label'   => _T('ecatalogue:sku'),
                     'rules'   => ''
                  )
            )
         );                                       
    }
    
    // Define test data
    public $test_data = array(
        array('id_article'=>1,'price'=>'90', 'priceold'=>'200', 'sku'=>'11111', 'quantity'=>'100', 'weight'=>'10', 
              'width'=>'20', 'height'=>'30', 'length'=>'40','id_equipment'=>1,'extra1'=>'','extra2'=>'','extra3'=>'','extra4'=>'',
              'is_composite'=>0,'is_separate'=>1, 'sold_in_packages'=>0,'num_in_package'=>1,'titre'=>'Test article 1','id_rubrique'=>1,'id_secteur'=>1),
        array('id_article'=>2,'price'=>'80', 'priceold'=>'190', 'sku'=>'22222', 'quantity'=>'50', 'weight'=>'11', 
              'width'=>'21', 'height'=>'31', 'length'=>'41','id_equipment'=>1,'extra1'=>'','extra2'=>'','extra3'=>'','extra4'=>'',
              'is_composite'=>0,'is_separate'=>1, 'sold_in_packages'=>0,'num_in_package'=>1,'titre'=>'Test article 2','id_rubrique'=>2,'id_secteur'=>1),
        array('id_article'=>3,'price'=>'70', 'priceold'=>'180', 'sku'=>'33333', 'quantity'=>'5', 'weight'=>'12', 
              'width'=>'22', 'height'=>'32', 'length'=>'42','id_equipment'=>2,'extra1'=>'','extra2'=>'','extra3'=>'','extra4'=>'',
              'is_composite'=>0,'is_separate'=>1, 'sold_in_packages'=>1,'num_in_package'=>2,'titre'=>'Test article 3','id_rubrique'=>3,'id_secteur'=>1),
        array('id_article'=>4,'price'=>'60', 'priceold'=>'170', 'sku'=>'44444', 'quantity'=>'0', 'weight'=>'13',
              'is_composite'=>0,'is_separate'=>1, 'sold_in_packages'=>1,'num_in_package'=>3,'width'=>'23', 'height'=>'33', 'length'=>'44','id_equipment'=>2,'extra1'=>'','extra2'=>'','extra3'=>'','extra4'=>'',
              'titre'=>'Test article 4','id_rubrique'=>4,'id_secteur'=>4),
    );
    
    /**
     *  Gets product price according to product's (inherited from rubrique) or given currency
	 *  If no currency given, and no currency found in DB, price will be outputed in current currency
     *  If product is composite and it have no price, total price of all it's composite products will be returned
     *  If product is composite and it have it's own price, this price will be returned
     *  
     *  @param int $id_article ID article
     *  @param string $currency_code Code of currency, in wich you want to get price. 
     *                              If you want to get price in product's currency, dont specify currency_code
     *  @param string $type Price type (field in ecatalogue_products table)
     *                      If you want to get not standart price, specify it's type, i.e. type="priceold"  
     */
    public function GetProductPrice($id_article, $currency_code = false, $type = 'price') {
        // If currency not specified, get article currency
        if (!$currency_code)
            $currency = $this->currency_mdl->GetCurrencyByIdArticle($id_article);
        else {
            $currency = $this->currency_mdl->select("code='".mysql_real_escape_string($currency_code)."'");
            $currency = $currency[0];
        }
        
        if (!isset($currency) || !$currency) {            
            throw new Exception("Currency for id_article #$id_article not found and currency with code \"$currency_code\" doesn't exist. Current currency also not found.");
        }   
        
        $product = $this->select_by_id($id_article);
        
        if (!isset($product) || !$product || empty($product)) {
            throw new Exception("Product #$id_article doesn't exist!");
        } 
        if (!isset($product[$type]))
            throw new Exception("Products table hasn't got \"$type\" field!");
        
        $price_precision = lire_config('ecatalogue/price_pricision'); if (!$price_precision) $price_precision = 2;
        
        $price = $product[$type]*$currency['rate'];        
        // If price isn't defined and product is composite - we'll calculate total price of all it's products                
        if (!$price && $product['is_composite'] && $type!='priceold') { 
            $comp_articles = $this->composite_art_mdl->select('id_composite='.intval($product['id_article']));
            foreach ($comp_articles as $comp_art) {
                $comp_product = $this->select_by_id($comp_art['id_article']);
                $price += $comp_product['price']*$currency['rate']*$comp_art['quantity'];
            }
        }
             
        //$price = $product[$type]*$currency['rate'];
        return round($price, $price_precision);
    }
    
    /**
     *  Override parent function
     */
    public function insert($data) {
        // If id_equipment doesn't exist, do auto increment
        if (!isset($data['id_equipment'])) {
            $data['id_equipment'] = $this->GetMaxIdEquipment()+1;
        }
        
        return parent::insert($data);
    }
    
    /**
     *  Gets max id_equipment in ecatalogue_products table
     */
    public function GetMaxIdEquipment() {
        $products = $this->select();
        $max = 0;
        foreach ($products as $product) {
            if ($product['id_equipment'] > $max)
                $max = $product['id_equipment'];    
        }
        return $max;       
    }
} 
?>